package br.com.sovi.resources;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mock.web.MockServletConfig;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.sun.jersey.spi.spring.container.servlet.SpringServlet;

public abstract class AbstractMockJerseyTestCase {

	protected final Logger logger = LoggerFactory.getLogger(getClass());

	protected SpringServlet dispatcher;

	protected MockServletContext servletContext;

	private final static String contextPath = "/glomer-server/rest";

	private final ContextLoaderListener contextListener;

	public AbstractMockJerseyTestCase() {
		this.servletContext = new MockServletContext();

		this.servletContext.addInitParameter("contextConfigLocation",
				"classpath*:META-INF/*-context.xml,classpath:META-INF/development.xml");

		final ServletContextEvent e = new ServletContextEvent(this.servletContext);
		this.contextListener = new ContextLoaderListener();
		this.contextListener.contextInitialized(e);

		this.servletContext.setContextPath(contextPath);
		final MockServletConfig servletConfig = new MockServletConfig(this.servletContext, "dispatcher");

		this.dispatcher = new SpringServlet();
		try {
			this.dispatcher.init(servletConfig);
		}
		catch (final ServletException e1) {
			e1.printStackTrace();
		}
	}

	@Override
	protected void finalize() throws Throwable {
		super.finalize();

		this.contextListener.contextDestroyed(new ServletContextEvent(this.servletContext));
		this.dispatcher.destroy();
	}

	@SuppressWarnings("unchecked")
	public <T> T getBean(final String nome) {
		final WebApplicationContext applicationContext = WebApplicationContextUtils
				.getRequiredWebApplicationContext(this.dispatcher.getServletContext());
		return (T) applicationContext.getBean(nome);
	}

}